package com.tianshi.user.controller;

import com.tianshi.entity.UserAddresses;
import com.tianshi.entity.Users;
import com.tianshi.user.service.UserAddressService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/userAddress")
public class UserAddressesController {
    @Autowired
    private UserAddressService userAddressService;
    //根据用户id查询地址列表
    @GetMapping("/searchByUserId")
    public List<UserAddresses> searchByUserId(Long userId, HttpSession session) {
        //从session中获取当前登录用户的信息
        Users user = (Users) session.getAttribute("loginUser");
        userId = user.getUserId();
        System.out.println("当前登录用户的id：" + userId);
        List<UserAddresses> userAddresses = userAddressService.searchByUserId(userId);
        session.setAttribute("userAddresses", userAddresses);
        return userAddresses;
    }
    //根据地址id删除地址信息
    @DeleteMapping("/deleteById")
    public ResponseEntity<String> deleteById(Long addressId) {
        System.out.println("要删除的地址id：" + addressId);
        int result = userAddressService.deleteById(addressId);   //返回受影响的行数
        if (result > 0){
            return ResponseEntity.ok("success");
        }else {
            return ResponseEntity.ok("error");
        }
    }
    @PutMapping("/updateAddress")
    public ResponseEntity<String> updateById(@RequestBody UserAddresses userAddresses, HttpSession session) {
        System.out.println("要修改的地址信息：" + userAddresses);
        int result = userAddressService.updateAddress(userAddresses);   //返回受影响的行数
        if (result > 0){
            //更新session中的地址列表
            List<UserAddresses> userAddressesList = userAddressService.searchByUserId(userAddresses.getUserId());
            session.setAttribute("userAddresses", userAddressesList);
            return ResponseEntity.ok("success");
        }else {
            return ResponseEntity.ok("error");
        }
    }
    @PostMapping("/addAddress")
    public ResponseEntity<String> add(@RequestBody UserAddresses userAddresses,HttpSession session) {
        Users user = (Users) session.getAttribute("loginUser");
        userAddresses.setUserId(user.getUserId());
        System.out.println("要新增的地址信息：" + userAddresses);
        int result = userAddressService.addAddress(userAddresses);   //返回受影响的行数
        if (result > 0){
            return ResponseEntity.ok("success");
        }else {
            return ResponseEntity.ok("error");
        }
    }
}
